﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class SpritesAnimation : MonoBehaviour
{
    [SerializeField] private float timeGap = 0.02f;
    private int index = 0;
    private int times;
    private bool isLoop;

    [SerializeField] private Image img = null;
    [SerializeField] private Sprite[] sprites;
    private Coroutine coroutine = null;

    public void Play(int _times,System.Action callback)
    {
        if (_times>0)
        {
            times = _times * sprites.Length;
            coroutine = StartCoroutine(PlayTimes(callback));
        }
        else
        {
            isLoop = true;
            coroutine = StartCoroutine(PlayLoops(callback));
        }
    }

    public void Stop()
    {
        if (coroutine!=null)
        {
            StopCoroutine(coroutine);
        }
        isLoop = false;
        index = 0;
        times = 0;
    }

    private void SetImg()
    {
        img.sprite = sprites[index];
        index = index >= sprites.Length-1 ? 0 : ++index;
    }

    IEnumerator PlayTimes(System.Action callback)
    {
        while (times>0)
        {
            SetImg();
            --times;
            yield return new WaitForSecondsRealtime(timeGap);
        }
        callback?.Invoke();
    }

    IEnumerator PlayLoops(System.Action callback)
    {
        while (isLoop)
        {
            SetImg();
            yield return new WaitForSecondsRealtime(timeGap);
        }
        callback?.Invoke();
    }
}
